package com.example.zhunongzonghe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.zhunongzonghe.beans.*;
import com.example.zhunongzonghe.dao.*;
import com.example.zhunongzonghe.entity.*;
import com.example.zhunongzonghe.service.IZnOrderService;
import com.example.zhunongzonghe.service.ZnFarmEvaluateService;
import com.example.zhunongzonghe.utils.BeanCopyUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;


@Service
public class ZnOrderServiceImpl extends ServiceImpl<ZnOrderMapper, ZnOrder> implements IZnOrderService {

    @Autowired
    ZnOrderMapper znOrderMapper;
    @Autowired
    ZnOrderDetailsMapper znOrderDetailsMapper;
    @Autowired
    ZnDeliveryAddressMapper znDeliveryAddressMapper;
    @Autowired
    ZnFarmproduceMapper znFarmproduceMapper;
    @Resource
    private ZnFarmSpecificationMapper specificationMapper;
    @Resource
    private ZnLogisticsMapper znLogisticsMapper;
    @Resource
    private ZnFarmEvaluateService znFarmEvaluateService;

    /**
     * 后台全部订单分页列表
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public Page<ZnOrderBean> queryOrderAll(Integer currentPage, Integer pageSize,Object searchInfo) {
        Page<ZnOrder> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<ZnOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(ZnOrder::getOrderNumber,searchInfo).or().like(ZnOrder::getUsername,searchInfo);
        Page<ZnOrder> orderPage = znOrderMapper.selectPage(page, queryWrapper);
        Page<ZnOrderBean> orderBeanPage = BeanCopyUtils.copyBeanPage(orderPage,ZnOrderBean.class);
        orderBeanPage.getRecords().forEach(orderBean->{
            LambdaQueryWrapper<ZnOrderDetails> detailsWrapper =new LambdaQueryWrapper<>();
            detailsWrapper.eq(ZnOrderDetails::getOrderId,orderBean.getOrderId());
            List<ZnOrderDetails> detailsList = znOrderDetailsMapper.selectList(detailsWrapper);
            List<ZnOrderDetailsBean> detailsBeanList = BeanCopyUtils.copyBeanList(detailsList,ZnOrderDetailsBean.class);
            orderBean.setZnOrderDetailsList(detailsBeanList);
            detailsBeanList.forEach(detailsBean->{
                ZnFarmproduce znFarmproduce = znFarmproduceMapper.selectById(detailsBean.getFarmId());
                ZnDeliveryAddress deliveryAddress = znDeliveryAddressMapper.selectById(detailsBean.getAddressId());
                ZnFarmSpecification specification = specificationMapper.selectById(detailsBean.getSpecId());
                ZnFarmSpecificationBean specificationBean =
                        BeanCopyUtils.copyBean(specification,ZnFarmSpecificationBean.class);
                detailsBean.setShopPicture(znFarmproduce.getShopPicture());
                detailsBean.setFarmName(znFarmproduce.getFarmName());
                detailsBean.setFarmIntro(znFarmproduce.getFarmIntro());
                detailsBean.setConsignee(deliveryAddress.getConsignee());
                detailsBean.setAddressDelivery(deliveryAddress.getAddressDelivery());
                detailsBean.setPhone(deliveryAddress.getPhone());
                detailsBean.setSpecificationBean(specificationBean);
            });
        });
        return orderBeanPage;
    }



    /**
     * 分页查询订单与订单详情
     * @param userName
     * @param pageId
     * @param pageSize
     * @return
     */
    @Override
    public IPage<ZnOrderBean> queryOrderAllWithPage(String userName, Integer pageId, Integer pageSize) {
        Page<ZnOrder> page = new Page<>(pageId, pageSize);
        LambdaQueryWrapper<ZnOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ZnOrder::getUsername, userName);
        IPage<ZnOrder> orderPage = znOrderMapper.selectPage(page, wrapper);
        List<ZnOrderBean> znOrderBeanList = new ArrayList<>();
        for (ZnOrder znOrder : orderPage.getRecords()) {
            ZnOrderBean znOrderBean = new ZnOrderBean();
            BeanUtils.copyProperties(znOrder, znOrderBean);
            LambdaQueryWrapper<ZnOrderDetails> detailsWrapper = new LambdaQueryWrapper<>();
            detailsWrapper.eq(ZnOrderDetails::getOrderId, znOrderBean.getOrderId());
            List<ZnOrderDetails> detailsList = znOrderDetailsMapper.selectList(detailsWrapper);
            List<ZnOrderDetailsBean> znOrderDetailsBeans = new ArrayList<>();
            for (ZnOrderDetails details : detailsList) {
                ZnOrderDetailsBean znOrderDetailsBean = new ZnOrderDetailsBean();
                BeanUtils.copyProperties(details, znOrderDetailsBean);
                znOrderDetailsBeans.add(znOrderDetailsBean);

                // 通过 farmId 和 addressId 查询相关信息
                ZnFarmproduce znFarmproduce = znFarmproduceMapper.selectById(znOrderDetailsBean.getFarmId());
                ZnDeliveryAddress znDeliveryAddress = znDeliveryAddressMapper.selectById(znOrderDetailsBean.getAddressId());
                ZnFarmSpecification znFarmSpecification = specificationMapper.selectById(details.getSpecId());
                ZnFarmSpecificationBean specBean = BeanCopyUtils.copyBean(znFarmSpecification,ZnFarmSpecificationBean.class);
                znOrderDetailsBean.setAddressDelivery(znDeliveryAddress.getAddressDelivery());
                znOrderDetailsBean.setConsignee(znDeliveryAddress.getConsignee());
                znOrderDetailsBean.setPhone(znDeliveryAddress.getPhone());
                znOrderDetailsBean.setFarmName(znFarmproduce.getFarmName());
                znOrderDetailsBean.setFarmIntro(znFarmproduce.getFarmIntro());
                znOrderDetailsBean.setShopPicture(znFarmproduce.getShopPicture());
                znOrderDetailsBean.setSpecificationBean(specBean);
            }
            znOrderBean.setZnOrderDetailsList(znOrderDetailsBeans);
            znOrderBeanList.add(znOrderBean);
        }
        // 将结果封装到 IPage 中返回
        IPage<ZnOrderBean> resultPage = new Page<>(pageId, pageSize, orderPage.getTotal());
        resultPage.setRecords(znOrderBeanList);
        return resultPage;
    }

    @Override
    public void buyNow(ZnOrderBean znOrderBean,String username) {
        ZnOrder znOrder = BeanCopyUtils.copyBean(znOrderBean,ZnOrder.class);
        znOrder.setOrderNumber(generateOrderNumber());
        znOrder.setUsername(username);
        znOrder.setPayStatus(0);
        znOrder.setDeliverStatus(0);
        znOrder.setTakeStatus(0);
        znOrder.setLogisticsId(-1);
        znOrder.setCourierNumber("-1");
        znOrder.setEvaluateStatus(0);
        znOrder.setCreateTime(LocalDateTime.now());
        znOrder.setUpdateTime(LocalDateTime.now());
        znOrderMapper.insert(znOrder);
        ZnOrderDetails znOrderDetails = new ZnOrderDetails();
        znOrderDetails.setOrderId(znOrder.getOrderId());
        znOrderDetails.setAddressId(znOrder.getAddressId());
        znOrderDetails.setCount(znOrderBean.getCount());
        znOrderDetails.setFarmId(znOrderBean.getFarmInfo().getFarmId());
        znOrderDetails.setUnitPrice(znOrderBean.getSpecInfo().getZnSpecPrice());
        znOrderDetails.setTotalPrice(znOrderBean.getTotalPrice());
        znOrderDetails.setSpecId(znOrderBean.getSpecInfo().getId());
        znOrderDetails.setEvaStatus(0);
        znOrderDetailsMapper.insert(znOrderDetails);
    }

    @Override
    public ZnOrder getOneOrder(String orderNumBer) {
        LambdaQueryWrapper<ZnOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZnOrder::getOrderNumber,orderNumBer);
        ZnOrder znOrder = znOrderMapper.selectOne(queryWrapper);
        return znOrder;
    }

    @Override
    public Page<ZnOrderBean> nonPaymentAll(Integer currentPage, Integer pageSize, Object searchInfo) {
        Page<ZnOrder> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<ZnOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZnOrder::getPayStatus,0).like(ZnOrder::getOrderNumber,searchInfo)
                .or().eq(ZnOrder::getPayStatus,0).like(ZnOrder::getUsername,searchInfo);
        Page<ZnOrder> orderPage = znOrderMapper.selectPage(page, queryWrapper);
        Page<ZnOrderBean> orderBeanPage = BeanCopyUtils.copyBeanPage(orderPage,ZnOrderBean.class);
        orderBeanPage.getRecords().forEach(orderBean->{
            LambdaQueryWrapper<ZnOrderDetails> detailsWrapper =new LambdaQueryWrapper<>();
            detailsWrapper.eq(ZnOrderDetails::getOrderId,orderBean.getOrderId());
            List<ZnOrderDetails> detailsList = znOrderDetailsMapper.selectList(detailsWrapper);
            List<ZnOrderDetailsBean> detailsBeanList = BeanCopyUtils.copyBeanList(detailsList,ZnOrderDetailsBean.class);
            orderBean.setZnOrderDetailsList(detailsBeanList);
            detailsBeanList.forEach(detailsBean->{
                ZnFarmproduce znFarmproduce = znFarmproduceMapper.selectById(detailsBean.getFarmId());
                ZnDeliveryAddress deliveryAddress = znDeliveryAddressMapper.selectById(detailsBean.getAddressId());
                ZnFarmSpecification specification = specificationMapper.selectById(detailsBean.getSpecId());
                ZnFarmSpecificationBean specificationBean =
                        BeanCopyUtils.copyBean(specification,ZnFarmSpecificationBean.class);
                detailsBean.setShopPicture(znFarmproduce.getShopPicture());
                detailsBean.setFarmName(znFarmproduce.getFarmName());
                detailsBean.setFarmIntro(znFarmproduce.getFarmIntro());
                detailsBean.setConsignee(deliveryAddress.getConsignee());
                detailsBean.setAddressDelivery(deliveryAddress.getAddressDelivery());
                detailsBean.setPhone(deliveryAddress.getPhone());
                detailsBean.setSpecificationBean(specificationBean);
            });
        });
        return orderBeanPage;
    }

    @Override
    public Page<ZnOrderBean> notYetShipped(Integer currentPage, Integer pageSize, Object searchInfo) {
        Page<ZnOrder> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<ZnOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZnOrder::getPayStatus,1)
                .eq(ZnOrder::getDeliverStatus,0)
                .like(ZnOrder::getOrderNumber,searchInfo)
                .or().eq(ZnOrder::getPayStatus,1)
                .eq(ZnOrder::getDeliverStatus,0)
                .like(ZnOrder::getUsername,searchInfo);
        Page<ZnOrder> orderPage = znOrderMapper.selectPage(page, queryWrapper);
        Page<ZnOrderBean> orderBeanPage = BeanCopyUtils.copyBeanPage(orderPage,ZnOrderBean.class);
        orderBeanPage.getRecords().forEach(orderBean->{
            LambdaQueryWrapper<ZnOrderDetails> detailsWrapper =new LambdaQueryWrapper<>();
            detailsWrapper.eq(ZnOrderDetails::getOrderId,orderBean.getOrderId());
            List<ZnOrderDetails> detailsList = znOrderDetailsMapper.selectList(detailsWrapper);
            List<ZnOrderDetailsBean> detailsBeanList = BeanCopyUtils.copyBeanList(detailsList,ZnOrderDetailsBean.class);
            orderBean.setZnOrderDetailsList(detailsBeanList);
            detailsBeanList.forEach(detailsBean->{
                ZnFarmproduce znFarmproduce = znFarmproduceMapper.selectById(detailsBean.getFarmId());
                ZnDeliveryAddress deliveryAddress = znDeliveryAddressMapper.selectById(detailsBean.getAddressId());
                ZnFarmSpecification specification = specificationMapper.selectById(detailsBean.getSpecId());
                ZnFarmSpecificationBean specificationBean =
                        BeanCopyUtils.copyBean(specification,ZnFarmSpecificationBean.class);
                detailsBean.setShopPicture(znFarmproduce.getShopPicture());
                detailsBean.setFarmName(znFarmproduce.getFarmName());
                detailsBean.setFarmIntro(znFarmproduce.getFarmIntro());
                detailsBean.setConsignee(deliveryAddress.getConsignee());
                detailsBean.setAddressDelivery(deliveryAddress.getAddressDelivery());
                detailsBean.setPhone(deliveryAddress.getPhone());
                detailsBean.setSpecificationBean(specificationBean);
            });
        });
        return orderBeanPage;
    }

    @Override
    public Page<ZnOrderBean> notReceive(Integer currentPage, Integer pageSize, Object searchInfo) {
        Page<ZnOrder> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<ZnOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZnOrder::getPayStatus,1)
                .eq(ZnOrder::getDeliverStatus,1)
                .eq(ZnOrder::getTakeStatus,0)
                .like(ZnOrder::getOrderNumber,searchInfo)
                .or().eq(ZnOrder::getPayStatus,1)
                .eq(ZnOrder::getDeliverStatus,1)
                .eq(ZnOrder::getTakeStatus,0)
                .like(ZnOrder::getUsername,searchInfo);
        Page<ZnOrder> orderPage = znOrderMapper.selectPage(page, queryWrapper);
        Page<ZnOrderBean> orderBeanPage = BeanCopyUtils.copyBeanPage(orderPage,ZnOrderBean.class);
        orderBeanPage.getRecords().forEach(orderBean->{
            LambdaQueryWrapper<ZnOrderDetails> detailsWrapper =new LambdaQueryWrapper<>();
            detailsWrapper.eq(ZnOrderDetails::getOrderId,orderBean.getOrderId());
            List<ZnOrderDetails> detailsList = znOrderDetailsMapper.selectList(detailsWrapper);
            ZnLogistics znLogistics = znLogisticsMapper.selectById(orderBean.getLogisticsId());
            ZnLogisticsBean znLogisticsBean = BeanCopyUtils.copyBean(znLogistics,ZnLogisticsBean.class);
            List<ZnOrderDetailsBean> detailsBeanList = BeanCopyUtils.copyBeanList(detailsList,ZnOrderDetailsBean.class);
            orderBean.setZnOrderDetailsList(detailsBeanList);
            orderBean.setZnLogisticsBean(znLogisticsBean);
            detailsBeanList.forEach(detailsBean->{
                ZnFarmproduce znFarmproduce = znFarmproduceMapper.selectById(detailsBean.getFarmId());
                ZnDeliveryAddress deliveryAddress = znDeliveryAddressMapper.selectById(detailsBean.getAddressId());
                ZnFarmSpecification specification = specificationMapper.selectById(detailsBean.getSpecId());
                ZnFarmSpecificationBean specificationBean =
                        BeanCopyUtils.copyBean(specification,ZnFarmSpecificationBean.class);
                detailsBean.setShopPicture(znFarmproduce.getShopPicture());
                detailsBean.setFarmName(znFarmproduce.getFarmName());
                detailsBean.setFarmIntro(znFarmproduce.getFarmIntro());
                detailsBean.setConsignee(deliveryAddress.getConsignee());
                detailsBean.setAddressDelivery(deliveryAddress.getAddressDelivery());
                detailsBean.setPhone(deliveryAddress.getPhone());
                detailsBean.setSpecificationBean(specificationBean);
            });
        });
        return orderBeanPage;
    }

    @Override
    public Page<ZnOrderBean> AllNoRefund(Integer currentPage, Integer pageSize, Object searchInfo) {
        Page<ZnOrder> page = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<ZnOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZnOrder::getPayStatus,2).like(ZnOrder::getOrderNumber,searchInfo);
        Page<ZnOrder> orderPage = znOrderMapper.selectPage(page, queryWrapper);
        Page<ZnOrderBean> orderBeanPage = BeanCopyUtils.copyBeanPage(orderPage,ZnOrderBean.class);
        orderBeanPage.getRecords().forEach(orderBean->{
            LambdaQueryWrapper<ZnOrderDetails> detailsWrapper =new LambdaQueryWrapper<>();
            detailsWrapper.eq(ZnOrderDetails::getOrderId,orderBean.getOrderId());
            List<ZnOrderDetails> detailsList = znOrderDetailsMapper.selectList(detailsWrapper);
            List<ZnOrderDetailsBean> detailsBeanList = BeanCopyUtils.copyBeanList(detailsList,ZnOrderDetailsBean.class);
            orderBean.setZnOrderDetailsList(detailsBeanList);
            detailsBeanList.forEach(detailsBean->{
                ZnFarmproduce znFarmproduce = znFarmproduceMapper.selectById(detailsBean.getFarmId());
                ZnDeliveryAddress deliveryAddress = znDeliveryAddressMapper.selectById(detailsBean.getAddressId());
                ZnFarmSpecification specification = specificationMapper.selectById(detailsBean.getSpecId());
                ZnFarmSpecificationBean specificationBean =
                        BeanCopyUtils.copyBean(specification,ZnFarmSpecificationBean.class);
                detailsBean.setShopPicture(znFarmproduce.getShopPicture());
                detailsBean.setFarmName(znFarmproduce.getFarmName());
                detailsBean.setFarmIntro(znFarmproduce.getFarmIntro());
                detailsBean.setConsignee(deliveryAddress.getConsignee());
                detailsBean.setAddressDelivery(deliveryAddress.getAddressDelivery());
                detailsBean.setPhone(deliveryAddress.getPhone());
                detailsBean.setSpecificationBean(specificationBean);
            });
        });
        return orderBeanPage;
    }

    @Override
    public List<ZnOrderDetailsBean> selectOrderDetails(Integer OrderId) {
        LambdaQueryWrapper<ZnOrderDetails> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZnOrderDetails::getOrderId,OrderId);
        List<ZnOrderDetails> detailsList = znOrderDetailsMapper.selectList(queryWrapper);
        List<ZnOrderDetailsBean> beanList = BeanCopyUtils.copyBeanList(detailsList,ZnOrderDetailsBean.class);
        beanList.forEach(details->{
            ZnFarmEvaluateBean evaluateBean = znFarmEvaluateService.getEvaluateId(details.getEvaluateId());
            ZnFarmproduce znFarmproduce = znFarmproduceMapper.selectById(details.getFarmId());
            ZnDeliveryAddress deliveryAddress = znDeliveryAddressMapper.selectById(details.getAddressId());
            ZnFarmSpecification specification = specificationMapper.selectById(details.getSpecId());
            ZnFarmSpecificationBean specificationBean =
                    BeanCopyUtils.copyBean(specification,ZnFarmSpecificationBean.class);
            details.setShopPicture(znFarmproduce.getShopPicture());
            details.setFarmName(znFarmproduce.getFarmName());
            details.setFarmIntro(znFarmproduce.getFarmIntro());
            details.setConsignee(deliveryAddress.getConsignee());
            details.setAddressDelivery(deliveryAddress.getAddressDelivery());
            details.setPhone(deliveryAddress.getPhone());
            details.setSpecificationBean(specificationBean);
            details.setEvaluateBean(evaluateBean);
        });
        return beanList;
    }

    @Override
    public void updateTakeStatus(String orderNumBer, String username) {
        LambdaQueryWrapper<ZnOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZnOrder::getOrderNumber,orderNumBer).eq(ZnOrder::getUsername,username);
        ZnOrder znOrder = znOrderMapper.selectOne(queryWrapper);
        LambdaQueryWrapper<ZnOrderDetails> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ZnOrderDetails::getOrderId,znOrder.getOrderId());
        List<ZnOrderDetails> detailsList = znOrderDetailsMapper.selectList(wrapper);
        detailsList.forEach(details->{
            ZnFarmproduce znFarmproduce = znFarmproduceMapper.selectById(details.getFarmId());
            znFarmproduce.setSalesVolume(znFarmproduce.getSalesVolume() + details.getCount());
            znFarmproduceMapper.updateById(znFarmproduce);
            ZnFarmSpecification znFarmSpecification = specificationMapper.selectById(details.getSpecId());
            znFarmSpecification.setInventory(znFarmSpecification.getInventory()-details.getCount());
            specificationMapper.updateById(znFarmSpecification);
        });
        znOrder.setTakeStatus(1);
        znOrderMapper.updateById(znOrder);
    }

    public static String generateOrderNumber() {
        // 获取当前时间戳
        long timestamp = System.currentTimeMillis();

        // 格式化日期部分，例如：yyyyMMddHHmmss
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String datePart = dateFormat.format(new Date(timestamp));

        // 生成随机数部分，例如：0000 到 9999
        Random random = new Random();
        int randomPart = random.nextInt(10000);

        // 组合订单号
        String orderNumber = datePart + String.format("%04d", randomPart);

        return orderNumber;
    }
}
